// pages/cart/submitOrder/submitOrder.js
const Controllers = require('../../controllers/Controller.js').controller;
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    globalStype:'',
    cartList: [],
    price: 0,
    num: 0,
    couponPrice: 0,
    couponAccountId: '',
    inputLengt: 0,
    desc: '',
    isBalance: true,
    payType: "wx",
    isCoupon: true,
    total: 0,
    paytotal:0,
    shopId: '',
    isGood:false,
    marketNo:null,
    options:'',
    myInformationdata:{
      vip:0,
      balance:0
    },
    userId:'',
    coupongoodsids:[],
    isuseCoupon:1,
    getMyCouponPagenum:0,
    isPin:true
  },
  onLoad: function (options) {
    this.setData({globalStype:app.globalData.globalStype})
    if (app.globalData.shopId) {
      this.setData({
        shopId: app.globalData.shopId
      })
    }
    if(options){
      this.setData({
        options:options
      })
      this.getcartlists()
      
    }
  },
  getcartlists(){
    // 获取列表
    let options=this.data.options
    let cartList
    if (options.list) {//购物车跳转过来的
      cartList = JSON.parse(options.list)
    }else if(options.isGood){//直接购买
      console.log(options.good)
      let good = JSON.parse(decodeURIComponent(options.good))
      console.log("good",good)
      if(!good.num){
        good.num = 1
      }
      good.goodsType = good.type
      cartList = []
      cartList.push(good)
      this.setData({
        isGood:options.isGood,
        marketNo:options.marketNo
      })
    }
    this.setData({cartList})
    
  },
  cart(isMyCouponPage=false){
    var cartList=this.data.cartList;
    var total=0
    var num=0
    var paytotal=0
    cartList.forEach(item => {
      if (item.goodsType == 2) {
        this.setData({
          isBalance: false
        })
      }
      var price=0;
      if((this.data.myInformationdata.vip==1 || this.data.myInformationdata.vip==2) && item.vipPrice && item.vipPrice>=0){
        price=item.vipPrice;
      }else{
        price=item.price;
      }
      if(this.data.marketNo && item.marketList && item.marketList.length>0 && item.marketList[0].pinPrice && item.marketList[0].pinPrice>0){
        price=item.marketList[0].pinPrice
      }
      if(this.data.isCoupon && this.data.coupongoodsids.length>0){
        for(let item2 of this.data.coupongoodsids){
          if(item2==item.goodsId){
            price=(item.price-this.data.couponPrice)>0?(item.price-this.data.couponPrice):0
          }
        }
      }
      total=total+price*item.num;
      num=num+item.num
    });
    
    if(this.data.isCoupon && this.data.coupongoodsids.length<=0){
      paytotal=total-this.data.couponPrice
    }else{
      paytotal=total
    }

    this.setData({
      total,
      paytotal,
      num,
    })
    if(!isMyCouponPage){
      this.getMyCouponPage()
    }
   
  },
  myInformation(){
    //获取数据
    Controllers.myInformation({shopId:this.data.shopId}).then(res => {
      this.setData({
        myInformationdata:res.data.accountRelation,
        userId: res.data.id
      })
      this.cart()
      
    }).catch(res=>{
      this.cart()
      
    })
  },
  //获取未使用的优惠券列表
  getMyCouponPage() {
    var cartList=this.data.cartList;
    let list = cartList.filter(item => item.goodsType == 0)
    let list2 = cartList.filter(item => item.goodsType == 1)
    if ((list.length <=0 && list2.length <=0) || this.data.marketNo) {
      this.setData({
        isCoupon: false
      })
      
    }else{
      let goodsIdsattr=[];
      for(let item of this.data.cartList){
        goodsIdsattr.push(item.goodsId)
      }
      let goodsIds=goodsIdsattr.join(',')

      Controllers.canUseCoupon({ shopId: this.data.shopId, accountId: this.data.userId,goodsIds:goodsIds,totalPrice:this.data.total }).then(res => {
        if (res.code == 1) {
          if(res.data && res.data.length>0 && this.data.isuseCoupon==1){
            let ishascoupon=false
            for(let item of res.data){
              if(this.data.couponAccountId==item.id){
                ishascoupon=true;
                break;
              }
            }
            if(!ishascoupon){
              this.setData({
                couponPrice: res.data[0].couponPrice,
                couponAccountId: res.data[0].id
              })
              if(res.data[0].couponType==2){
                this.setData({
                  coupongoodsids:res.data[0].ids.split(',')
                })
              }
            }
          }else{
            this.setData({
              couponPrice: 0,
              couponAccountId: ''
            })
          }
        }
        this.cart(true)
      }).catch(res=>{
        this.cart(true)
      })
    }
  },
  gocoupon(){
    let goodsIdsattr=[];
    for(let item of this.data.cartList){
      goodsIdsattr.push(item.goodsId)
    }
    let goodsIds=goodsIdsattr.join(',')
    wx.navigateTo({
      url: '/pages/cart/coupon/coupon?totalPrice='+this.data.total+'&goodsIds='+goodsIds+'&couponAccountId='+this.data.couponAccountId
    })
  },
  
  onShow: function () {
    if (app.globalData.coupon && this.data.isCoupon) {
      this.setData({
        couponPrice: app.globalData.coupon.couponPrice,
        couponAccountId: app.globalData.coupon.id
      })
    }
    if(app.globalData.isuseCoupon){
      this.setData({isuseCoupon:app.globalData.isuseCoupon})
    }
    this.myInformation()
  },
  onUnload: function () {
    this.setData({
      couponPrice: 0,
      couponAccountId: ''
    })
    if(app.globalData.coupon){
      app.globalData.coupon.couponPrice=0
      app.globalData.coupon.id=''
    }
  },
  //键盘输入触发
  length(e) {
    let length = e.detail.value.length
    let value = e.detail.value
    // console.log(length)
    this.setData({
      desc: value,
      inputLengt: length
    })
  },
  //跳转详情
  goDetail(e) {
    let url = e.currentTarget.dataset['url'];
    wx.navigateTo({
      url: url
    })
  },
  //选择支付方式
  selectType(e) {
    let payType = e.currentTarget.dataset['type'];
    if (payType == "yr") {
      if (this.data.isBalance) {
        this.setData({
          payType
        })
      }
    } else {
      this.setData({
        payType
      })
    }
  },
  //删除商品
  deleteCart(e) {
    let index = e.currentTarget.dataset['index'];
    let ids
    let cartList = this.data.cartList
    let num = 0
    let total = 0
    ids = cartList[index].id
    Controllers.delGoods({ shopId: this.data.shopId, cartIds: ids }).then(res => {
      if (res.code == 1) {
        cartList.splice(index, 1);
        if(cartList.length==0){
          wx.reLaunch({
            url: "/pages/cart/index/index"
          })
        }
        this.setData({
          cartList
        })
        this.cart()
        wx.showToast({
          title: "删除成功",
          icon: 'none',
          duration: 800
        });
      }
    })
  },
  //支付
  pay() {
    var balance=this.data.myInformationdata.balance;
    if(this.data.payType == "yr" && this.data.paytotal>balance){
      wx.showToast({
        title: "余额不足",
        icon: 'none',
        duration: 800
      });
      return 
    }
    if(this.data.isGood){
      this.goodPay()
    }else{
      this.cartPay()
    }
  },
  //购物车支付
  cartPay(){
    let ids = []
    this.data.cartList.forEach(item => {
      ids.push(item.id)
    })
    ids = ids.join(',')
    let data={
      shopId: this.data.shopId,
      cartIds:ids,
      desc: this.data.desc
    }
    if(this.data.couponAccountId){
      data.couponAccountId=this.data.couponAccountId
    }
    Controllers.cartSettlement(data).then(res => {
      if (res.code == 1) {
        if (this.data.payType == "yr" || this.data.paytotal<=0) {
          this.yrPay(res.data.orderNo)
        } else {
          this.weChatPay(res.data)
          // this.paySuccess(res.data)
          
        }
        this.setData({
          couponPrice: 0,
          couponAccountId: ''
        })
        if(app.globalData.coupon){
          app.globalData.coupon.couponPrice=0
          app.globalData.coupon.id=''
        }
      }
    })
  },
  //直接购买
  goodPay(){
    let goodsId = this.data.cartList[0].goodsId
    let num = this.data.cartList[0].num
    let data={
      shopId: this.data.shopId,
      goodsId:goodsId,
      num:num,
      couponAccountId:this.data.couponAccountId,
      desc: this.data.desc
    }
    this.setData({
      goodsId:goodsId
    })
    if(this.data.marketNo){
      data.marketNo=this.data.marketNo
    }

    Controllers.goodsSettlement(data).then(res=>{
      if (res.code == 1) {
        this.setData({
          orderId:res.data.orderNo
        })
        if (this.data.payType == "yr" || this.data.paytotal<=0) {
          this.yrPay(res.data.orderNo,res.data.id)
        } else {
          this.weChatPay(res.data,res.data.id)
          // this.paySuccess(res.data)
        }
        this.setData({
          couponPrice: 0,
          couponAccountId: ''
        })
        if(app.globalData.coupon){
          app.globalData.coupon.couponPrice=0
          app.globalData.coupon.id=''
        }
      }
    })
  },
  //加减商品数量
  addSubtract(e){
    if(this.data.marketNo){
      return
    }
    let type = e.currentTarget.dataset['type'];
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let num = 0;
    let total = 0
    if(type == "add"){
      cartList[index].num += 1
    }else if(cartList[index].num > 1){
      cartList[index].num -= 1
    }
    if(this.data.isGood){
      this.setData({
        cartList
      })
      this.cart()
    }else{
      Controllers.updateCart({shopId:this.data.shopId,cartId:cartList[index].id,num:cartList[index].num}).then(res => {
        if(res.code == 1){
          this.setData({
            cartList
          })
          this.cart()
        }
      })
    }
  },
  changenums(e){
    if(this.data.marketNo){
      return
    }
    let index = e.currentTarget.dataset['index'];
    let cartList = this.data.cartList;
    let num = 0;
    let total = 0
    cartList[index].num = Number(e.detail.value)
    
    if(this.data.isGood){
      this.setData({
        cartList
      })
      this.cart()
    }else{
      Controllers.updateCart({shopId:this.data.shopId,cartId:cartList[index].id,num:cartList[index].num}).then(res => {
        if(res.code == 1){
          this.setData({
            cartList
          })
          this.cart()
        }
      })
    }
  },
  //余额支付
  yrPay(orderNo,orderId) {
    console.log(orderId)
    Controllers.balancePay({ shopId: this.data.shopId, orderNo: orderNo }).then(res => {
      if (res.code == 1) {
        setTimeout(() => {
          let goodsType=this.data.cartList[0].goodsType;
          let goodsId=this.data.cartList[0].goodsId;
          
          if(this.data.isGood){
            // wx.navigateBack({
            //   delta: 1
            // })
            if(this.data.cartList[0].isPin==true){
              wx.showToast({
                title: '拼团支付完成',
                duration:2000
              })
              setTimeout(function(){
                wx.navigateTo({
                  url: '/pages/my/service-order/service-order?id=1',
                })
              },2000)
            }else{
              if(goodsType==0){
                wx.navigateTo({
                  url: '/pages/cart/submitOrder/success/success?goodsId='+goodsId+"&orderId="+orderId+"&goodsType="+goodsType+"&orderNo="+orderNo,
                })
              }else{
                wx.navigateTo({
                  url: '/pages/cart/submitOrder/success/success?goodsId='+goodsId+"&orderId="+orderId+"&goodsType=1",
                })
              }
            }
          }else{
            // wx.reLaunch({
            //   url: "/pages/cart/index/index"
            // })
            wx.navigateTo({
              url: '/pages/cart/submitOrder/success/success?goodsType=1'
            })
          }
        },1000)
        
        // wx.showToast({
        //   title: "支付成功",
        //   icon: 'none',
        //   duration: 1000
        // });
      }
    })
  },
  paySuccess(data) {
    Controllers.paySuccess({ shopId: this.data.shopId, orderNo: data.orderNo,orderId: data.id,accountId: data.accountId ?data.accountId :''}).then(res => {
      if (res.code == 1) {
        var that=this;
        setTimeout(() => {
          if(that.data.isGood){
            wx.navigateBack({
              delta: 1
            })
          }else{
            wx.reLaunch({
              url: "/pages/cart/index/index"
            })
          }
        },1000)
    
        wx.showToast({
          title: "下单成功",
          icon: 'none',
          duration: 1000
        });
      }
    })
  },

  weChatPay(data,orderId) {
    var that=this;
    let openId=app.globalData.openId
    Controllers.weChatPay({ shopId: this.data.shopId, orderNo: data.orderNo,frontUrl:"mp:///pages/Index/Index",openId:openId}).then(res => {
      // let url=res.data;
      // url=encodeURIComponent(url);
      // console.log(url);
      // wx.redirectTo({
      //   url: '/pages/weixinlink/weixinlink?url='+url,
      // })
      let data=JSON.parse(res.data);
      console.log(data)
      console.log(orderId)
      wx.requestPayment({
        nonceStr: data.nonceStr,
        package: data.package,
        paySign: data.paySign,
        timeStamp: data.timeStamp,
        signType: data.signType,
        success(res){
            let goodsType=that.data.cartList[0].goodsType;
            let goodsId=that.data.cartList[0].goodsId;
            let orderNo=orderNo;
            let order=orderId;
            if(that.data.isGood){
              // wx.navigateBack({
              //   delta: 1
              // })
              if(that.data.cartList[0].isPin==true){
                wx.showToast({
                  title: '拼团支付完成',
                  duration:2000
                })
                setTimeout(function(){
                  wx.navigateTo({
                    url: '/pages/my/service-order/service-order?id=1',
                  })
                },2000)
              }else{
                if(goodsType==0){
                  wx.navigateTo({
                    url: '/pages/cart/submitOrder/success/success?goodsId='+goodsId+"&orderId="+order+"&goodsType="+goodsType+"&orderNo="+orderNo,
                  })
                }else{
                  wx.navigateTo({
                    url: '/pages/cart/submitOrder/success/success?goodsId='+goodsId+"&orderId="+order+"&goodsType=1",
                  })
                }
              }
            }else{
              // wx.reLaunch({
              //   url: "/pages/cart/index/index"
              // })
              wx.navigateTo({
                url: '/pages/cart/submitOrder/success/success?goodsType=1'
              })
            }
          wx.showToast({
            title: "支付成功",
            icon: 'none',
            duration: 1000
          });
        },
        fail(res){
          setTimeout(() => {
            if(that.data.isGood){
              wx.navigateBack({
                delta: 1
              })
            }else{
              wx.reLaunch({
                url: "/pages/cart/index/index"
              })
            }
          },1000)
      
          wx.showToast({
            title: "支付失败",
            icon: 'none',
            duration: 1000
          });
        }
      })
    }).catch(res=>{
      
      setTimeout(() => {
        if(that.data.isGood){
          wx.navigateBack({
            delta: 1
          })
        }else{
          wx.reLaunch({
            url: "/pages/cart/index/index"
          })
        }
      },1000)
  
      wx.showToast({
        title: "支付失败",
        icon: 'none',
        duration: 1000
      });
    })
  },
})